package com.bibrApp.difu.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.google.gson.Gson;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author dj
 * @date 2020/3/2
 * SharedPreferences 工具类
 */
public class ShareUtils<T> {

  private SharedPreferences mSharePreferences;

  public ShareUtils(Context context, String name) {
    mSharePreferences = context.getSharedPreferences(name, Context.MODE_PRIVATE);
  }

  /**
   * 保存List
   *
   * @param tag
   * @param datalist
   */
  public <U> void setDataList(String tag, List<U> datalist) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    if (null == datalist || datalist.size() <= 0) {
      return;
    }

    Gson gson = new Gson();
    // 转换成json数据，再保存
    String strJson = gson.toJson(datalist);
    editor.clear();
    editor.putString(tag, strJson);
    editor.apply();
  }

  /**
   * 获取List
   *
   * @param tag
   * @return
   */
  public ArrayList<T> getDataList(String tag, Class<T[]> cls) {
    ArrayList<T> datalist = new ArrayList<T>();
    String strJson = mSharePreferences.getString(tag, null);
    if (null == strJson) {
      return datalist;
    }
    Gson gson = new Gson();
//    datalist = gson.fromJson(strJson, new TypeToken<List<T>>(){}.getType());
    datalist = new ArrayList<>(Arrays.asList(gson.fromJson(strJson , cls)));
    return datalist;
  }
  /**
   * 保存bean数据，数据必须序列化
   * @param t
   * @param keyName
   * @param <T>
   */
  public <T extends Serializable> void saveData(T t, String keyName) {

    ByteArrayOutputStream bos;
    ObjectOutputStream oos = null;
    try {
      bos = new ByteArrayOutputStream();
      oos = new ObjectOutputStream(bos);
      oos.writeObject(t);
      byte[] bytes = bos.toByteArray();
      String ObjStr = Base64.encodeToString(bytes, Base64.DEFAULT);
      SharedPreferences.Editor editor = mSharePreferences.edit();
      editor.putString(keyName, ObjStr);
      editor.commit();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (oos != null) {
        try {
          oos.flush();
          oos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }

  /**
   * 获取bean数据
   * @param keyName
   * @param <T>
   * @return
   */
  public <T extends Serializable> T getData(String keyName) {
    byte[] bytes = Base64.decode(mSharePreferences.getString(keyName, ""), Base64.DEFAULT);
    ByteArrayInputStream bis;
    ObjectInputStream ois = null;
    T obj = null;
    try {
      bis = new ByteArrayInputStream(bytes);
      ois = new ObjectInputStream(bis);
      obj = (T) ois.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (ois != null) {
        try {
          ois.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return obj;
  }
  public void saveString(String key, String value) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.putString(key, value);
    editor.commit();
  }

  public String readString(String key) {
    return mSharePreferences.getString(key, null);
  }

  public void saveInt(String key, int value) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.putInt(key, value);
    editor.commit();
  }

  public int getInt(String key, int defaultValue) {
    return mSharePreferences.getInt(key, defaultValue);
  }

  public void saveLong(String key, long value) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.putLong(key, value);
    editor.commit();
  }

  public void saveBytes(String key, byte[] bts) {
    if (bts == null || bts.length < 1) {
      return;
    }
    SharedPreferences.Editor editor = mSharePreferences.edit();
    StringBuilder builder = new StringBuilder();
    builder.append(bts[0]);
    for (int i = 1; i < bts.length; i++) {
      builder.append("&");
      builder.append(bts[i]);
    }
    editor.putString(key, builder.toString());
    editor.commit();
  }

  public long readLong(String key, long defaultValue) {
    return mSharePreferences.getLong(key, defaultValue);
  }

  public void saveFloat(String key, float value) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.putFloat(key, value);
    editor.commit();
  }

  public float readFloat(String key, float defaultValue) {
    return mSharePreferences.getFloat(key, defaultValue);
  }

  public void saveBoolean(String key, boolean value) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.putBoolean(key, value);
    editor.commit();
  }

  public boolean getBoolean(String key, boolean defaultBoolean) {
    return mSharePreferences.getBoolean(key, defaultBoolean);
  }

  public byte[] readBytes(String key) {
    try {
      String value = mSharePreferences.getString(key, "");
      String[] bs = value.split("&");
      if (bs != null && bs.length > 0) {
        byte[] vs = new byte[bs.length];
        for (int i = 0; i < bs.length; i++) {
          vs[i] = (byte) (Integer.parseInt(bs[i]));
        }
        return vs;
      }
      return null;
    } catch (Exception e) {
      return null;
    }
  }

  public void deleteData(String key) {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.remove(key);
    editor.commit();
  }

  public void clearAll() {
    SharedPreferences.Editor editor = mSharePreferences.edit();
    editor.clear();
    editor.apply();
    editor.commit();
  }
}
